package com.xiaomazi.edu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaomazi.common.utils.R;
import com.xiaomazi.edu.client.UcenterClient;
import com.xiaomazi.edu.dto.front.CommentFrontDTO;
import com.xiaomazi.edu.entity.Course;
import com.xiaomazi.edu.service.CourseService;
import com.xiaomazi.servicebase.entity.UserInfo;
import com.xiaomazi.servicebase.exception.LLXYException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaomazi.edu.mapper.CommentMapper;
import com.xiaomazi.edu.entity.Comment;
import com.xiaomazi.edu.service.CommentService;
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService{

    @Autowired
    private UcenterClient ucenterClient;

    @Autowired
    private CourseService courseService;

    /**
     * 根据课程Id获取课程评论
     * @param commentFrontDTO 课程id 评论内容
     * @return 课程评论数据 总记录条数
     */
    @Override
    public R getCommentsByCourseId(CommentFrontDTO commentFrontDTO) {
        if (null == commentFrontDTO || commentFrontDTO.getCourseId() == null){
            throw new LLXYException(20001,"课程id有误");
        }
        IPage<Comment> page = new Page<>(commentFrontDTO.getCurrent(),commentFrontDTO.getSize());
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id",commentFrontDTO.getCourseId());
        queryWrapper.orderByDesc("gmt_create");
        page = this.page(page,queryWrapper);
        return R.ok().data("total",page.getTotal()).data("rows",page.getRecords());
    }

    /**
     * 添加课程评论
     * @param comment 课程信息
     * @return ok
     */
    @Override
    public R saveComment(Comment comment,String userId) {
        if (comment == null || comment.getCourseId() == null) {
            throw new LLXYException(20001,"课程id不能为空");
        }
        Course course = courseService.getById(comment.getCourseId());
        if (null != course){
            comment.setTeacherId(course.getTeacherId());
        }
        UserInfo userInfo = ucenterClient.getUserInfoByUserId(userId);
        if (null != userInfo){
            comment.setNickname(userInfo.getNickname());
            comment.setAvatar(userInfo.getAvatar());
            comment.setMemberId(userInfo.getMemberId());
        }
        this.save(comment);
        return R.ok();
    }
}
